package datastructure.link;

public class LC24 {

    public ListNode swapPairs1(ListNode head) {
        ListNode pre = new ListNode(0);
        pre.next = head;
        ListNode current = pre;
        ListNode left;
        ListNode right;
        while (current.next != null && current.next.next != null) {
            left = current.next;
            right = current.next.next;
            current.next = right;
            left.next = right.next;
            right.next = left;
            current = current.next.next;
        }
        return pre.next;
    }

    /**
     *
     * @param head
     * @return
     * 每次递归后返回交换完成的首节点
     */
    public ListNode swapPairs(ListNode head) {
        if(head== null || head.next == null){
            return head;
        }
        //当前节点的下一个节点
        ListNode next = head.next;
        //当前节点的新的下一个节点需要指向交换后的首节点
        head.next = swapPairs(next.next);
        next.next = head;
        //返回的是交换后的首节点
        return next;
    }
}
